package com.ruoyi.aitymyy.utils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.aitcommon.api.DBOperation;
import com.ruoyi.aitcommon.service.SQLService;
import com.ruoyi.aitcommon.utils.FlowUtils;
import com.ruoyi.aitcommon.utils.JSONResult;
import com.ruoyi.aitcommon.utils.ListMapUtils;
import com.ruoyi.aitcommon.utils.MapUtils;
import com.ruoyi.aitymyy.api.YmyyAPI;
import com.ruoyi.aitymyy.config.BaseMapConfig;
import com.ruoyi.aitymyy.config.OuterDBConfig;

@Component
public class YmyyUtils {
	public static final String KZNAME = "interface";
	public static final String KZFIELD = "IMPORT_ID";
	@Autowired
	DBOperation dboper;
	@Autowired
	YmyyAPI ymyyApi;
	@Autowired
	SQLService sqlsv;

//	获取中间库的控制表ID
	public static String getKZID(String tablename) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String kzid = tablename + "_" + sdf.format(new Date()) + "_" + FlowUtils.getFlowID().toString();
		return kzid;
	}

//	构造控制表对象
	public static Map<String, Object> newKZData(String id, int count) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
		String time = sdf.format(new Date());
		Map<String, Object> kz = new HashMap<String, Object>();
		kz.put("import_id", id);
		kz.put("post_start_time", time);
		kz.put("post_end_time", time);
		kz.put("record_count", count);
		kz.put("post_status", "成功");
		return kz;
	}

//	回写控制表信息
	public static String getkzUpdateSQL(String importid,String status) throws Exception {
		String sql;
		// 回写中间库成功标识
		if (importid == null||StringUtils.isBlank(importid))
			throw new Exception("import_id 获取为空");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
		String time = sdf.format(new Date());
		sql = "update interface set get_start_time='%s',get_end_time='%s',get_status='%s'\r\n" + "where import_id='%s'";
		sql = String.format(sql, time, time, status, importid);
		return sql;
	}
	
//	构造供应商回写表
	public static List<Map<String, Object>> getGYSRetData(String table, JSONArray aret) {
		List<Map<String,Object>> gretlist=new ArrayList<>();
		for (Object object : aret) {
			JSONObject json=(JSONObject)object;
			
			JSONObject gret=new JSONObject();
			gret.put("import_id", YmyyUtils.getKZID(table));
			gret.put("code", json.getString("field1")); //用友code
			gret.put("name", json.getString("code")); //商销code
			gretlist.add(gret);
		}
		return gretlist;
	}
	
	public JSONObject gysImport(String importid) throws Exception {
		String sql;
		String rettable="interface_distributor_return";
		sql="select dist.* from interface_distributor dist where import_id='"+importid+"'";
		List<Map<String, Object>> datalist = sqlsv.execQuery(sql, OuterDBConfig.zjk);
		if(datalist==null || datalist.size()==0) throw new Exception("查询数据为空");
		
//			转换数据
		List<Map<String, Object>> wlist = ListMapUtils
				.transObjectValuetoKey(datalist, BaseMapConfig.gysmap);
		
//			写入供应商
		JSONObject parm=new JSONObject();
		parm.put("data", wlist);
		JSONObject ret = ymyyApi.cubasdocSave(parm.toJSONString());
//			JSONResult.jsonAssert(ret);
		
//		回写供应商编码
		JSONArray aret = JSONResult.getDataArray(ret);
		if(aret==null||aret.size()==0) 
			return JSONResult.error("返回数据为空");
		List<Map<String, Object>> gretlist = YmyyUtils.getGYSRetData(rettable, aret);
		sqlsv.mapInsert(gretlist, OuterDBConfig.zjk, rettable, null, null);
//		供应商回写表的控制表
		Map<String, Object> newKZData = YmyyUtils.newKZData(YmyyUtils.getKZID(rettable), datalist.size());
		sqlsv.mapInsert(Arrays.asList(newKZData), OuterDBConfig.zjk, YmyyUtils.KZNAME, null, null);
		
//			回写控制信息和错信信息
		return UpdateZJKInfo(importid, ret,(erritem)->{
			String sql1="UPDATE interface_distributor set error_message='%s'\r\n"
					+ "where import_id='%s' and code='%s'";
			sql1=String.format(sql1, erritem.getString("msg")
					,importid,erritem.getString("code")); //商销供应商编码
			return sql1;
		});
	}

//	回写中间库信息
	public JSONObject UpdateZJKInfo(String importid, JSONObject ret, KZUpdateFunc errsql)
			throws Exception {
		String sql;
		JSONArray aret = JSONResult.getDataArray(ret);
		
		if(!JSONResult.isSuccess(ret)) {
//			导入存在错误数据
			List<String> sqls=new ArrayList<String>();
			if(aret!=null&&aret.size()>0) {
				for (Object ob : aret) {
					JSONObject json=(JSONObject)ob;
					if(!json.getString("msg").equals("")) {
						sqls.add(errsql.oper(json));
					}
				}
				if(sqls.size()>0)
					sqlsv.execBatchUpdate(sqls, OuterDBConfig.zjk);
			}
//			回写控制表
			sql=YmyyUtils.getkzUpdateSQL(importid,"失败");
			sqlsv.execUpdate(sql, OuterDBConfig.zjk);
			return JSONResult.success("供应商导入失败");
		}else {
//				导入成功
			sql=YmyyUtils.getkzUpdateSQL(importid,"成功");
			sqlsv.execUpdate(sql, OuterDBConfig.zjk);
			return JSONResult.success("供应商导入成功");
		}
	}
	
	public JSONObject gysaddrImport(String importid) throws Exception {
		String sql="select dist.* from interface_distributor_shipment dist"
				+ " where import_id='"+importid+"'";
		List<Map<String, Object>> datalist = sqlsv.execQuery(sql, OuterDBConfig.zjk);
		if(datalist.size()==0) throw new Exception("查询数据为空");
		
//		转换数据
		List<Map<String, Object>> wlist = ListMapUtils
				.transObjectValuetoKey(datalist, BaseMapConfig.gysdzmap);
//		写入供应商地址
		JSONObject parm=new JSONObject();
		parm.put("data", wlist);
		JSONObject ret = ymyyApi.custaddrSave(parm.toJSONString());
//		JSONResult.jsonAssert(ret);
		
//		回写控制信息和错信信息
		return UpdateZJKInfo(importid, ret,(erritem)->{
			String sql1="UPDATE interface_distributor_shipment set error_message='%s'\r\n"
					+ "where import_id='%s' and distributor_code='%s' and address='%s'";
			sql1=String.format(sql1, erritem.getString("msg") //错误消息
					,importid
					,erritem.getString("field1") //商销供应商编码
					,erritem.getString("code")); //供应商地址名称
			return sql1;
		});
	}
	
	public JSONObject lxrImport(String importid) throws Exception{
//		中间库联系人查询
		String sql = "select *,1 systype,'0001' corp,'YM01' doclist \r\n"
				+ "from interface_contacts \r\n"
				+ "where import_id='"+importid+"'";
		List<Map<String, Object>> datalist=sqlsv.execQuery(sql, OuterDBConfig.zjk);
		if(datalist.size()==0) throw new Exception("查询数据为空");
		
//		转换数据
		List<Map<String, Object>> wlist = ListMapUtils
				.transObjectValuetoKey(datalist, BaseMapConfig.lxrmap);
		
//		写入联系人
		JSONObject parm=new JSONObject();
		parm.put("data", wlist);
		JSONObject ret = ymyyApi.defdocSave(parm.toJSONString());
//		JSONResult.jsonAssert(ret);
		
//		回写控制表信息
		return UpdateZJKInfo(importid, ret,(erritem)->{
			String sql1="UPDATE interface_contacts set error_message='%s'\r\n"
					+ "where import_id='%s' and code='%s'";
			sql1=String.format(sql1, erritem.getString("msg") //错误消息
					,importid
					,erritem.getString("code")); //联系人编码
			return sql1;
		});
	}
	
	/**
	 * 数据同步的通用处理
	 * 
	 * @param days  同步天数
	 * @param table 插入表名
	 * @param sql   查询SQL
	 * @return JSONObject
	 * @throws Exception
	 */
	public JSONObject dataSync(Double days, String table, String sql) throws Exception {
		// 查询sql
		sql = String.format(sql, days);
		// 获取数据
//		List<Map<String, Object>> datalist = sqlsv.execQuery(sql, OuterDBConfig.ymyy);
		JSONObject parm=new JSONObject();
		MapUtils.putPathObject("data.sql", parm, sql);
		JSONObject retobj = ymyyApi.DBCommonQuery(parm.toJSONString());
		JSONResult.jsonAssert(retobj);
		List<Map<String,Object>> datalist = JSONResult.getDataListMap(retobj);
		ListMapUtils.put(datalist, YmyyUtils.KZFIELD, YmyyUtils.getKZID(table));
		
		// 数据写入
		if (datalist != null) {
			// 写入中间库
			int iret = sqlsv.mapInsert(datalist, OuterDBConfig.zjk, table, null, "TS,ts");
			if (iret == 0)
				return JSONResult.error("插入数据为0");
			// 写入控制表
			Map<String, Object> newKZData = YmyyUtils.newKZData(YmyyUtils.getKZID(table), datalist.size());
			iret = sqlsv.mapInsert(Arrays.asList(newKZData), OuterDBConfig.zjk, YmyyUtils.KZNAME, null, null);
			return JSONResult.success();
		} else
			return JSONResult.error("没有数据！");
	}
}

interface KZUpdateFunc{
	String oper(JSONObject json);
}

